#include <stdio.h>
#include <stdlib.h>

struct PageNode
{
	int value;
	struct PageNode *next;
};

int comp(const void *a,const void *b)
{
	double num =  *(double *)b - *(double *)a;
	if(num > 0)   return  1;
	if(num < 0)   return  -1;
	return 0;
}

int main()
{
	double alpha = 0.15;
	int N = 247573;
	int M = 30;
	int ***data = malloc(sizeof(int**)*28);
	int PageOutDegree[N];
	char line[1000];
	char *cTemp;
	double PageRank[N];
	double Itemp[N];
	struct PageNode PageLink[N];
	struct PageNode *node[N];
	struct PageNode *temp;
	int i,j,k,a,b,c,t,n,bool,lineNumber;
	FILE *fr,*fw;
	/**数据初始化**/
	for(i = 0;i < 30;i++)
	{
		data[i] = malloc(sizeof(int *)*50);
		for(j = 0;j < 50;j++)
		{
			data[i][j] = malloc(sizeof(int)*900);
			for(k = 0;k < 900;k++)
				data[i][j][k] = -1;
		}
	}
	for(i = 0;i < N;i++)
	{
		PageOutDegree[i] = 0;
		node[i] = &PageLink[i];
		PageRank[i] = 1.0/N;
		Itemp[i] = alpha/N;
		PageLink[i].value = -1;
	}
	/**读取并初步处理数据**/	
	fr = fopen("wt2g_inlinks","r");
	t = 0;
	while (fgets(line,1000,fr) != NULL)
	{
		cTemp = line;
		bool = 0;
		while(sscanf(cTemp,"WT%d-B%d-%d %n",&a,&b,&c,&n) != EOF)
		{
			cTemp += n;
			if(data[a][b][c] == -1)
			{
				data[a][b][c] = t;
				t++;
			}
			if(bool == 0)
			{
				bool = 1;
				lineNumber = data[a][b][c];
			}
			else
			{
				PageOutDegree[data[a][b][c]]++;	//处理OutDegree
				node[data[a][b][c]]->value = lineNumber;//连接结构
				node[data[a][b][c]]->next = malloc(sizeof(struct PageNode));
				node[data[a][b][c]] = node[data[a][b][c]]->next;
				node[data[a][b][c]]->value = -1; // 如果是没有其他网页链接到该网页，设该网页的value为-1。
			}
		}
	}
	/**迭代阶段**/
	for(i = 0;i < M;i++)
	{
		for(j = 0;j < N;j++)
		{
			temp = &PageLink[j];
			if(PageOutDegree[j] > 0)
			{
				while(temp->value != -1)
				{
					Itemp[temp->value] += (1-alpha) * PageRank[j]/PageOutDegree[j];
					temp = temp->next;
				}
			}
		}
		for(j = 0;j < N;j++)
		{
			PageRank[j] = Itemp[j];
			Itemp[j] = alpha/N;
		}
	}
	/**根据PR大小进行排序**/
	qsort(PageRank,N,sizeof(double),comp);
	/**输出PR和作为对比**/
	double Dtemp = 0;
	for(j = 0;j < N;j++)
		Dtemp += PageRank[j];
	printf("PageRank Sum: %lf\n",Dtemp);
	/**输出结果**/
	fw = fopen("../res/PageRank_Simple_Result","w");
	for(i = 0;i < N;i++)
		fprintf(fw,"%lf\n",PageRank[i]);
	fclose(fw);
	return 0;
}
